<template>
  <div>
    <el-button type="primary" @click="AddWeb = true">添加网络</el-button>
    <!-- 表格展示 -->
    <el-scrollbar>
      <div class="min-w-1000px">
        <el-table :data="networkList" style="width: 100%; margin-top: 20px">
          <el-table-column prop="id" label="ID" width="50" />
          <el-table-column prop="action" label="规则" />
          <el-table-column prop="direction" label="网络方向" />
          <el-table-column prop="protocol" label="协议类型" />
          <el-table-column prop="local_port_range" label="本地端口范围" />
          <el-table-column prop="local_ip_address" label="本地IP地址" />
          <el-table-column prop="remote_port_range" label="远程端口范围" />
          <el-table-column prop="remote_ip_address" label="远程IP地址" />
          <el-table-column label="操作" width="100">
            <template #default="scope">
              <el-button
                size="small"
                type="danger"
                :loading="delButton"
                @click="handleDelete(scope.row.id)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <div class="flex-c m-t-20px">
          <el-pagination
            background
            layout="prev, pager, next,sizes"
            :total="total"
            :current-page="WebPage.page"
            :page-size="WebPage.count"
            :page-sizes="[1, 10, 20, 30]"
            @update:current-page="handleCurrentPageChange"
            @update:page-size="handlePageSizeChange"
          />
        </div>
      </div>
    </el-scrollbar>
    <el-dialog
      v-model="AddWeb"
      title="创建网络规则"
      width="600"
      draggable
      overflow
    >
      <el-alert
        show-icon
        title="注意：请务必了解网络规则和相关操作，确保自己清楚所执行的每一个步骤，否则可能会导致不可预见的后果。"
        type="warning"
        :closable="false"
      />
      <div>
        <el-form
          ref="formRef"
          :model="formWeb"
          label-width="auto"
          style="max-width: 600px"
        >
          <el-form-item label="规则" prop="action">
            <el-radio-group v-model="formWeb.action">
              <el-radio value="Allow">允许</el-radio>
              <el-radio value="Deny">拒绝</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="网络方向" prop="direction">
            <el-radio-group v-model="formWeb.direction">
              <el-radio value="Outbound">出站</el-radio>
              <el-radio value="Inbound">入站</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="协议类型" prop="protocol">
            <el-radio-group v-model="formWeb.protocol">
              <el-radio value="Any">全部</el-radio>
              <el-radio value="TCP">TCP</el-radio>
              <el-radio value="UDP">UDP</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="本地端口范围" prop="local_port_range">
            <el-input
              v-model="formWeb.local_port_range"
              placeholder="一个端口则填端口，多个则表示为 80-100"
            />
          </el-form-item>
          <el-form-item label="本地IP地址" prop="local_ip_address">
            <el-input
              v-model="formWeb.local_ip_address"
              placeholder="本地IP地址，支持CIDR或IP地址"
            />
          </el-form-item>
          <el-form-item label="远程端口范围" prop="remote_port_range">
            <el-input
              v-model="formWeb.remote_port_range"
              placeholder="一个端口则填端口，多个则表示为 80-100"
            />
          </el-form-item>
          <el-form-item label="远程IP地址" prop="remote_ip_address">
            <el-input
              v-model="formWeb.remote_ip_address"
              placeholder="远程IP地址，支持CIDR或IP地址"
            />
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="AddWeb = false">关闭</el-button>
          <el-button type="primary" :loading="loading" @click="submitForm">
            提交
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, defineEmits, defineProps } from "vue";
import { ElForm } from "element-plus";
import {
  getVirtualAccessList,
  createAccessControl,
  deleteAccessControl
} from "@/api/virtual";
import type { ComponentSize, FormInstance, FormRules } from "element-plus";
import { message } from "@/utils/message";

const props = defineProps(["ID"]);
onMounted(async () => {
  await getNetworkList();
});

const WebPage = reactive({
  page: 1,
  count: 10,
  instance_id: props.ID
});
const handleCurrentPageChange = async page => {
  WebPage.page = page;
  await getNetworkList();
};

const handlePageSizeChange = async count => {
  WebPage.count = count;
  await getNetworkList();
};

const networkList = ref([]);
const total = ref(0);
const getNetworkList = async () => {
  await getVirtualAccessList(WebPage).then(res => {
    console.log(res);
    networkList.value = res.data.data;
    total.value = res.data.count;
  });
};

// 添加数据卷信息
const formWeb = reactive({
  instance_id: props.ID, // 虚拟机ID
  action: "Allow", // 可选: allow/deny
  direction: "Outbound", // 可选: Outbound/Inbound
  protocol: "Any", // 可选: all/tcp/udp
  local_port_range: "", // 可选: 本地端口范围
  local_ip_address: "", // 可选: 本地IP地址
  remote_port_range: "", // 可选: 远程端口范围
  remote_ip_address: "" // 可选: 远程IP地址
});

// // 自定义验证函数
// const validatePortRange = (rule: any, value: string, callback: any) => {
//   const portRangeRegex = /^(\d{1,5}(-\d{1,5})?)$/;
//   if (!portRangeRegex.test(value)) {
//     callback(new Error("端口范围格式不正确"));
//   } else {
//     callback();
//   }
// };

// const validateIPAddress = (rule: any, value: string, callback: any) => {
//   const ipRegex = /^(?:[0-9]{1,3}\.){3}[0-9]{1,3}(?:\/[0-9]{1,2})?$/;
//   if (!ipRegex.test(value)) {
//     callback(new Error("IP地址格式不正确，支持CIDR或IP地址"));
//   } else {
//     callback();
//   }
// };

// // 表单验证规则
// const rules = reactive<FormRules>({
//   action: [{ required: true, message: "请选择规则", trigger: "change" }],
//   direction: [{ required: true, message: "请选择网络方向", trigger: "change" }],
//   protocol: [{ required: true, message: "请选择协议类型", trigger: "change" }],
//   local_port_range: [
//     { required: true, message: "请输入本地端口范围", trigger: "blur" },
//     { validator: validatePortRange, trigger: "blur" }
//   ],
//   local_ip_address: [
//     { required: true, message: "请输入本地IP地址", trigger: "blur" },
//     { validator: validateIPAddress, trigger: "blur" }
//   ],
//   remote_port_range: [
//     { required: true, message: "请输入远程端口范围", trigger: "blur" },
//     { validator: validatePortRange, trigger: "blur" }
//   ],
//   remote_ip_address: [
//     { required: true, message: "请输入远程IP地址", trigger: "blur" },
//     { validator: validateIPAddress, trigger: "blur" }
//   ]
// });

const formRef = ref<InstanceType<typeof ElForm>>();

const loading = ref(false);

const submitForm = async () => {
  try {
    loading.value = true; // 开始加载
    const valid = await formRef.value?.validate();
    if (valid) {
      console.log(formWeb);
      const res = await createAccessControl(formWeb);
      console.log(res);
      if (res.data.code === 200) {
        message("创建成功", { type: "success" });
        AddWeb.value = false;
      } else {
        message(res.data.data.msg, { type: "error" });
      }
      await getNetworkList();
    }
  } catch (error) {
    message("提交表单时发生错误，请稍后再试。", { type: "error" });
  } finally {
    loading.value = false; // 结束加载
  }
};

const AddWeb = ref(false);
const delButton = ref(false);

const handleDelete = async id => {
  delButton.value = true;
  await deleteAccessControl({ access_control_id: id }).then(async res => {
    if (res.data.code == 200) {
      message(res.data.data, { type: "success" });
      await getNetworkList();
    } else {
      message(res.data.data, { type: "error" });
    }
    delButton.value = false;
  });
};
</script>

<style scoped>
.ovf {
  overflow-x: auto;
}
</style>
